<template>
  <div class="pages addSaleOrder">
    <div class="pageLevel">
      <!-- 操作框 -->
      <div class="tableSearch">
        <el-button type="primary" @click="goBack()" size="mini">返回</el-button>
        <el-button type="primary" @click="submitForm('formdata')" size="mini">保存</el-button>
        <el-button type="primary" @click="addgoods()" size="mini">添加商品</el-button>
      </div>
      <!-- 表单 -->
      <el-form :model="formdata" :rules="rules" ref="formdata" label-width="120px" size="mini">
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户：" prop="shopName">
              <el-input v-model="formdata.shopName" disabled>
                <el-button :disabled="viewDis" type="primary" @click="dialogUser=true" slot="append" style="height:28px; color: #fff;background-color: #409eff;border-color: #409eff;">选择</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单状态：">
              <el-input v-model="orderSaleStatusArr[formdata.statusFlow]" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="交货日期：" prop="deliveryDate">
              <el-date-picker :disabled="viewDis" v-model="formdata.deliveryDate" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date" placeholder="选择交货日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据日期：" prop="orderDate">
              <el-date-picker :disabled="true" v-model="formdata.orderDate" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date" placeholder="选择交货日期"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="单据号：">
              <el-input v-model="formdata.saleCode" placeholder="单据号自动生成" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 物料表格 -->
      <div class="tableMain">
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column type="index" label="#" width="55"></el-table-column>
          <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
          <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
          <el-table-column prop="goodsName" label="商品" align="center" width="200">
          </el-table-column>
          <el-table-column prop="goodsSpec" label="规格型号" align="center" width="120px">
            <template slot-scope="scope">
              <div v-for="(item,index) in scope.row.goodsSpec" :key="index">
                <span v-if="item!=null">{{item.paramName}} :</span>
                <span v-if="item!=null"> {{item.paramValue}} </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="unitName" label="单位" align="center" width="200"></el-table-column>
          <el-table-column prop="purchaseNum" label="数量" align="center" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.purchaseNum" size="mini" type="text" style="width:100px" min="0"  oninput="if(value.length>8)value=value.slice(0,8)" onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="goodsPrice" label="单价" align="center">
          </el-table-column>
          <el-table-column prop="goodsAmount" label="总价" align="center">
            <template slot-scope="scope">
              <span v-if="!isNaN( (Number(scope.row.goodsPrice)*Number(scope.row.purchaseNum)).toFixed(2))">{{(Number(scope.row.goodsPrice)*Number(scope.row.purchaseNum)).toFixed(2)}}</span>
              <span v-if="isNaN( (Number(scope.row.goodsPrice)*Number(scope.row.purchaseNum)).toFixed(2))">0.00</span>
            </template>
          </el-table-column>
          <el-table-column v-if="!viewDis" align="center" label="操作" width="180">
            <template slot-scope="scope">
              <el-button type="text" @click="handleCancel(scope.$index)" size="mini">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 价钱计算 -->
      <div class="th-right">
        <el-form :model="formdata" :rules="rules" label-width="120px" size="mini">
          <el-row>
            <el-col :span="12">
              <el-form-item label="操作员：">
                <el-input v-model="formdata.creator" disabled></el-input>
              </el-form-item>
              <el-form-item label="备注：">
                <el-input :disabled="viewDis" v-model="formdata.remark" type="textarea" maxlength="50"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="商品总计：" prop="priceTotal">
                <el-input label-text-align="right" v-model="saleAmount" disabled></el-input>
              </el-form-item>
              <el-form-item label="运费：" prop="freight">
                <el-input :disabled="viewDis" v-model="formdata.freight" type="text" min="0" onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"></el-input>
              </el-form-item>
              <el-form-item label="应收总计：">
                <el-input v-model="formdataAllTotal" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 客户选择弹出框 -->
      <el-dialog title="客户清单" class="addshopname" :visible.sync="dialogUser" :closeOnClickModal="false" :closeOnPressEscape="false" width="60%">
        <i class="el-icon-close icon" @click="dialogUser=false"></i>
        <div class="operationBox tableSearch">
          <el-button size="mini" type="primary" @click="saveUser">选择</el-button>
          <el-button size="mini" @click="dialogUser=false">取消</el-button>
        </div>
        <div class="tableSearch tableSearchs">
          <i class="el-input__icon el-icon-search" @click="searchUser"></i>
          <el-form label-width="100px">
            <el-form-item label label-width="15px">
              <el-input class="input" v-model="selectData.userKeyword" size="small" placeholder="输入客户名称或编号"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="userArray" stripe border ref="singleTable" tooltip-effect="dark" highlight-current-row @current-change="changeFunUser">
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="shopCode" label="企业客户编码" align="center"></el-table-column>
          <el-table-column prop="name" label="企业客户名称" align="center"></el-table-column>
        </el-table>
        <div class="pageblock">
          <el-button size="mini" type="primary" class="Determine topage">确定</el-button>
          <el-pagination @size-change="handleSizeChangeUser" @current-change="handleCurrentChangeUser" :current-page="currentpageUser" :page-sizes="[5,10,20]" :page-size="pageSizeUser" layout="total, sizes, prev, pager, next, jumper" :total="totalUser"></el-pagination>
        </div>
      </el-dialog>

      <!-- 商品选择弹出框 -->
      <el-dialog title="商品选择" class="addshopname" :visible.sync="dialogGood" :closeOnClickModal="false" :closeOnPressEscape="false" width="66%">
        <i class="el-icon-close icon" @click="dialogGood=false"></i>
        <div class="operationBox tableSearch">
          <el-button size="mini" type="primary" @click="saveGood">选择</el-button>
          <el-button size="mini" @click="dialogGood=false">取消</el-button>
        </div>
        <div class="tableSearch tableSearchs">
          <i class="el-input__icon el-icon-search" @click="searchGoods"></i>
          <el-form label-width="100px">
            <el-form-item label label-width="15px">
              <el-input class="input" v-model="selectData.goodKeyword" size="small" placeholder="输入商品名称或编号"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="goodArray" stripe border ref="multipleTable" tooltip-effect="dark" @selection-change="changeFunGood" :row-key="getRowKeys">
          <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
          <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
          <el-table-column prop="goodsName" label="商品名称" align="center"></el-table-column>
          <el-table-column prop="customerName" label="企业客户" align="center" width="120"></el-table-column>
          <el-table-column prop="goodsSpec" label="规格型号" align="center" width="120px">
            <template slot-scope="scope">
              <div v-for="(item,index) in scope.row.goodsSpec" :key="index">
                <span v-if="item!=null">{{item.paramName}} :</span>
                <span v-if="item!=null"> {{item.paramValue}} </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="goodsPrice" label="价格" align="center"></el-table-column>
          <el-table-column prop="purchaseUnit" label="单位" align="center"></el-table-column>
          <el-table-column prop="isFreight" label="含运费" align="center">
            <template slot-scope="scope">
              <span v-show="scope.row.isFreight=='1'">含运费</span>
              <span v-show="scope.row.isFreight=='0'">不含运费</span>
            </template>
          </el-table-column>
          <el-table-column prop="freight" label="运费" align="center" width="170"></el-table-column>
        </el-table>
        <div class="pageblock">
          <el-button size="mini" type="primary" class="Determine topage">确定</el-button>
          <el-pagination @size-change="handleSizeChangeGood" @current-change="handleCurrentChangeGood" :current-page="currentpageGood" :page-sizes="[5,10,20]" :page-size="pageSizeGood" layout="total, sizes, prev, pager, next, jumper" :total="totalGood"></el-pagination>
        </div>
      </el-dialog>
    </div>
    <el-dialog title="提示" :visible.sync="dialogVisible2" width="30%">
      <span>商品总计发生变动,请重新确认运费</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="handleClose2">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import {
  findOrderPriceAgreementListPage,
  selectBaseShopPageList,
  selectGoodsSaleDetails,
  updateGoodsSale
} from "@/api";
import u from "@/util";
import s from "@/util/state";
export default {
  components: {},
  data() {
    return {
      // 获取row的key值
      getRowKeys(row) {
        return row.id;
      },
      amountBefore: 0,
      viewDis: false, // 查看时不可点击
      tableData: [], // 选择的物料数组
      dialogVisible2: false,
      orderSaleStatusArr:s.orderSaleStatusArr,//订单状态
      formdata: {
        userId: "",
        deliveryDate: "", // 交货日期
        statusFlow: "", // 订单状态
        orderDate: "", // 单据日期
        shopId: "", // 客户id
        shopName: "", // 客户名称
        goodsList: [], // 物料
        creator: "", // 操作人
        remark: "", // 备注
        purchaseAmount: 0, // 总计
        freight: 0, // 运费
        taxAmount: 0, // 税
        amount: 0 // 实收总计
      },
      ids: "",
      selectData: {
        userKeyword: "", // 客户搜索关键字
        goodKeyword: "" // 物料搜索关键字
      },
      dialogUser: false, // 选择客户弹窗
      dialogGood: false, // 选择物料弹窗
      selectionUser: [], // 选择的客户数组
      selectionGood: [], // 选择的物料数组
      userArray: [], // 客户数组
      goodArray: [], // 物料数组
      pageSizeUser: 5, // 客户弹窗分页
      currentpageUser: 1,
      totalUser: 0,
      pageSizeGood: 5, // 物料弹窗分页
      currentpageGood: 1,
      totalGood: 0,
      rules: {
        shopName: [{ required: true, message: "请选择客户", trigger: "blur" }],
        orderDate: [
          { required: true, message: "请选择单据日期", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    ...mapState({
      merchantId: state => state.merchantId,
      userId: state => state.userId,
    }),
    saleAmount: function() {
      let totalPrice = 0;
      this.freightNum = 0.0;
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].goodsAmount =
          this.tableData[i].goodsPrice * this.tableData[i].purchaseNum;
        totalPrice +=
          this.tableData[i].goodsPrice * this.tableData[i].purchaseNum;
          if(this.tableData[i].freight==undefined){
            this.tableData[i].freight=0
          }
          this.freightNum += this.tableData[i].freight * this.tableData[i].purchaseNum;
      }
      this.formdata.freight = isNaN(this.freightNum) ? 0:this.freightNum.toFixed(2);
      this.formdata.purchaseAmount = totalPrice.toFixed(2);
      return isNaN(totalPrice) ? 0 : totalPrice.toFixed(2);
    },
    formdataAllTotal: function() {
      let totalPrice = 0;
      totalPrice = Number(this.saleAmount) + Number(this.formdata.freight);
      if (totalPrice == NaN || totalPrice == 0) {
        this.formdata.amount = 0;
        totalPrice = 0;
        return totalPrice;
      } else {
        this.formdata.amount = totalPrice.toFixed(2);
        return totalPrice.toFixed(2);
      }
    }
  },
  mounted() {
    this.viewDis = false;
    this.enterprise(this.pageSizeUser, this.currentpageUser); // 获取客户列表
    this.init(); // 初始化表单数据
  },
  methods: {
    // 商品数量发生变化时确定按钮
    handleClose2() {
      this.dialogVisible2 = false;
      this.handleSave();
    },
    // 添加商品按钮
    addgoods() {
      if (this.formdata.shopName) {
        this.dialogGood = true;
      } else {
        this.$message({
          type: "error",
          message: "请先选择企业客户"
        });
      }
    },
    init() {
      this.id = u.getQuery("id");
      this.getDataById(this.id); // 查看该订单详情
    },
    // 点击保存，先验证表单
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.amountBefore != this.formdata.purchaseAmount) {
            this.dialogVisible2 = true;
          } else {
            this.handleSave();
          }
        } else {
          return false;
        }
      });
    },
    // 提交表单
    handleSave() {
      if (this.tableData.length == 0 || !this.tableData[0].goodsId) {
        this.$message({
          type: "error",
          message: "商品不能为空"
        });
        return false;
      }
      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].goodsNum <= 0) {
          this.$message({
            type: "error",
            message: "商品数量不能小于等于0"
          });
          return false;
        }
        this.tableData[i].goodsOrganizationSkuId = this.tableData[i].id;
      }
      let data = this.formdata;
      data.id = this.id;
      data.creator = this.userId;
      data.goodsList = JSON.stringify(this.tableData);
      data.saleAmount = this.formdata.purchaseAmount;
      data.amount = this.formdata.amount;
      updateGoodsSale(data).then(res => {
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: res.msg
          });
          u.routerTo("/order-center/sale-management/sale-salesorder");
        } 
      });
    },
    // 获取客户列表
    enterprise(pageSize, pageNum) {
      let data = {
        nameOrCode: this.selectData.userKeyword,
        pageSize: pageSize,
        pageNum: pageNum,
        status: 0,
        businessId: this.merchantId,
        type: 1
      };
      selectBaseShopPageList(data).then(res => {
        this.totalUser = res.data.pageTotal;
        this.userArray = res.data.list;
      });
    },
    // 商品列表数据
    getGoods(pageSize, pageNum) {
      let data = {
        pageSize: pageSize,
        pageNum: pageNum,
        customerId: this.ids,
        supplierId: this.merchantId,
        status: 0,
        agreementType: 0
      };
      findOrderPriceAgreementListPage(data).then(res => {
        if (res.data) {
          this.goodArray = res.data.list;
          this.totalGood = res.data.pageTotal;
        }
      });
    },
    // 点击返回按钮
    goBack() {
      history.back();
    },
    // 客户弹窗相关操作
    changeFunUser(val) {
      if (val) {
        this.selectionUser = val;
      } else {
        this.selectionUser = [];
      }
    },
    // 客户搜索按钮
    searchUser() {
      this.enterprise(this.pageSizeUser, 1);
    },
    handleSizeChangeUser(val) {
      this.pageSizeUser = val;
      this.currentpageUser = 1;
      this.enterprise(val, this.currentpageUser);
    },
    handleCurrentChangeUser(val) {
      this.currentpageUser = val;
      this.enterprise(this.pageSizeUser, val);
    },
    // 客户选择的值
    saveUser() {
      if (this.ids != this.selectionUser.id) {
        this.ids = this.selectionUser.id;
        this.tableData = [];
        if (this.tableData.length == 0) {
          this.tableData.push([{ goodsId: "" }]);
        }
      }
      this.getGoods(this.pageSizeGood, 1);
      this.formdata.shopName = this.selectionUser.name;
      this.dialogUser = false;
      this.tableData = [];
    },
    // 物料弹窗相关操作
    changeFunGood(val) {
      if (val) {
        this.selectionGood = val;
        for (let i = 0; i < this.selectionGood.length; i++) {
          this.selectionGood[i].unitName = this.selectionGood[i].purchaseUnit;
        }
      } else {
        this.selectionGood = [];
      }
    },
    // 商品搜索
    searchGoods() {
      this.getGoods(this.pageSizeGood, 1);
    },
    // 删除表格中选中的物料
    handleCancel(index) {
      this.tableData.splice(index, 1);
    },
    handleSizeChangeGood(val) {
      this.pageSizeGood = val;
      this.currentpageGood = 1;
      this.getGoods(val, this.currentpageGood);
    },
    handleCurrentChangeGood(val) {
      this.currentpageGood = val;
      this.getGoods(this.pageSizeGood, val);
    },
    // 商品选择的数据
    saveGood() {
      let a = [];
      for (let i = 0; i < this.selectionGood.length; i++) {
        this.selectionGood[i].purchaseNum = 0;
        for (let y = 0; y < this.tableData.length; y++) {
          if (this.selectionGood[i].goodsId == this.tableData[y].goodsId) {
            this.selectionGood.splice(i, 1);
          }
        }
      }
      this.dialogGood = false;
      this.selectionGood.forEach(ele => {
        this.tableData.push(JSON.parse(JSON.stringify(ele)));
      });
      this.$refs.multipleTable.clearSelection();
    },
    getdatetime(now, l = "-", m = ":") {
      now = new Date(now);
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      let date = now.getDate();
      let hour = now.getHours();
      let minute = now.getMinutes();
      // let seconds = now.getSeconds()
      if (month < 10) {
        month = "0" + month;
      }
      if (date < 10) {
        date = "0" + date;
      }
      if (hour < 10) {
        hour = "0" + hour;
      }
      if (minute < 10) {
        minute = "0" + minute;
      }
      return year + l + month + l + date;
    },
    // 查看时根据id获取详情
    getDataById(goodsSaleId) {
      let data = {
        id: goodsSaleId
      };
      selectGoodsSaleDetails(data).then(res => {
        if (res.code == 200 && res.data != null) {
          this.formdata = JSON.parse(JSON.stringify(res.data));
          this.tableData = res.data.goodsList;
          this.amountBefore= res.data.saleAmount
          this.formdata.orderDate = this.getdatetime(res.data.orderDate);
          this.formdata.deliveryDate = this.getdatetime(res.data.deliveryDate);
          this.ids = res.data.shopId;
          this.formdata.creator = res.data.userName;
           let freight = res.data.freight
           this.$nextTick(() => {
           this.formdata.freight = freight
          })
          this.getGoods(this.pageSizeGood, 1);
        } else if (res.code != 200) {
          this.$message({
            type: "error",
            message: res.msg
          });
        }
      });
    }
  }
};
</script>
<style scoped>
.th-right {
  margin-left: 568px;
  margin-top: 20px;
}
.tableSearchs {
  position: relative;
}
.tableSearchs .el-input__icon {
  position: absolute;
  top: 12px;
  left: 190px;
  z-index: 10;
  width: 25px;
  height: 35px;
}
</style>

